#!/bin/sh

# filename: configi3.sh
# deploy name: configi3
# auto open ~/.config/i3/config to edit with nano,vi,vim,nvim support
# todo: add more edtior support like kate, ...

# Define the i3 config file path
I3_CONFIG="$HOME/.config/i3/config"

# Check if the config file exists; create it if not
if [ ! -f "$I3_CONFIG" ]; then
    echo "i3 config file not found. Creating empty file at: $I3_CONFIG"
    mkdir -p "$(dirname "$I3_CONFIG")"
    touch "$I3_CONFIG"
fi

# Function to check if an editor exists
editor_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Default editor priority: nano > nvim > vim > vi
EDITOR=""
if editor_exists nano; then
    EDITOR=nano
elif editor_exists nvim; then
    EDITOR=nvim
elif editor_exists vim; then
    EDITOR=vim
elif editor_exists vi; then
    EDITOR=vi
else
    echo "Error: No text editor found (tried nano, nvim, vim, vi)"
    exit 1
fi

# Handle explicit editor arguments
case "$1" in
    -nano)
        if editor_exists nano; then
            EDITOR=nano
        else
            echo "Error: nano not found"
            exit 1
        fi
        ;;
    -vim)
        if editor_exists vim; then
            EDITOR=vim
        else
            echo "Error: vim not found"
            exit 1
        fi
        ;;
    -nvim)
        if editor_exists nvim; then
            EDITOR=nvim
        else
            echo "Error: nvim not found"
            exit 1
        fi
        ;;
    -vi)
        if editor_exists vi; then
            EDITOR=vi
        else
            echo "Error: vi not found"
            exit 1
        fi
        ;;
    "")
        # No argument: use default
        ;;
    *)
        echo "Error: Invalid argument. Supported: -nano, -vim, -nvim, -vi"
        exit 1
        ;;
esac

# Open the i3 config file with the selected editor
echo "Opening i3 config with $EDITOR: $I3_CONFIG"
exec "$EDITOR" "$I3_CONFIG"
